<?php


use Yaf\Controller_Abstract;
use Yaf\Dispatcher;

class AdvertisingController extends Controller_Abstract
{
    /**
     * get_img接口
     * 获取二维码
     * @return array|bool
     */
    public function getImgAction()
    {
        //获取用户信息
        $request = Dispatcher::getInstance()->getRequest();
        $user = UserModel::getUserModel($request);

        //获取二维码
        $model = new WeChatOpenLoginModel($user);
        $img = $model->getLoginImg();
        if (!$img) {
            return ResponeMessage::serviceErrMsg("获取二维码失败!");
        }
        return ResponeMessage::sucessMsg("获取成功", [
            'url' => $img,
            'uuid' => substr($img, strrpos($img, '/') + 1),
        ]);

    }


    /**
     * 验证是否扫码
     * 验证是否扫码
     * @return array|bool
     */
    public function checkLoginAction()
    {
        //获取用户信息
        $request = $this->getRequest();
        $userModel = UserModel::getUserModel($request);


        //获取二维码
        $model = new WeChatOpenLoginModel($userModel);
        $get = $request->getQuery();
        //检查登陆状态
        $err = $model->checkLoginStatus($get['uuid']);
        if ($err) {
            return ResponeMessage::clientErrMsg("错误信息:" . $err);
        }

        //登陆
        $err = $model->login();
        if ($err) {
            return ResponeMessage::clientErrMsg("错误信息:" . $err);
        }

        $cookieFile = $userModel->getCookieFile() . 'cookie.txt';
        if (!file_exists($cookieFile)) {
            return ResponeMessage::clientErrMsg("错误信息:" . "cookie文件不存在!");
        }

        $cookieStr = file_get_contents($cookieFile);

        return ResponeMessage::sucessMsg("获取成功", [
            'cookie_str' => $cookieStr,
        ]);

    }


    /**
     * 获取index的接口
     * @return array|bool
     */
    public function getIndexAction()
    {
        //获取用户信息
        $request = $this->getRequest();
        $userModel = UserModel::getUserModel($request);

        //逻辑
        $postArr = $this->getRequest()->getPost();
        if (empty($postArr)) {
            return ResponeMessage::clientErrMsg("错误信息:" . "ts_uid，pgv_pvid，pgv_info，g_tk数据为空!");
        }

        $cookFile = $userModel->getCookieFile() . "cookie.txt";

        $ts_uid = $postArr['ts_uid'];
        $pgv_pvid = $postArr['pgv_pvid'];
        $pgv_info = $postArr['pgv_info'];
        $g_tk = $postArr['g_tk'];

        $fp = file($cookFile);
        $gTkStr = end($fp);  // #g_tj:xxxxx
        //不存在这个字符串的时候给他造一个
        if (strpos($gTkStr, 'g_tj') === false) {
            $time = time();
            $data = '.a.weixin.qq.com	TRUE	/	FALSE	' . $time . '	pgv_pvid	' . $pgv_pvid . PHP_EOL . '.a.weixin.qq.com	TRUE	/	FALSE	' . $time . '	ts_uid	    ' . $ts_uid . PHP_EOL . '.a.weixin.qq.com	TRUE	/	FALSE	' . $time . '	ts_info	    ' . $pgv_info . PHP_EOL . '#g_tj:' . $g_tk;
            file_put_contents($cookFile, $data, FILE_APPEND);
            $fp = file($cookFile);
            $gTkStr = end($fp);  // #g_tj:xxxxx
        }

        $g_tk = substr($gTkStr, 6);
        return !empty($g_tk) ? ResponeMessage::sucessMsg("返回成功!", compact('g_tk')) : ResponeMessage::serviceErrMsg("没有获取到g_tk");
    }


    /**
     * 获取主页信息吧
     * @return array|bool
     */
    public function forurlAction()
    {

        $request = $this->getRequest();

        $model = new WeChatOpenLoginModel(UserModel::getUserModel($request));

        $get = $request->getQuery();
        if (empty($get['g_tk'])) {
            return ResponeMessage::clientErrMsg("错误信息:" . "g_tk数据为空!");
        }

        $model->setGTk($get['g_tk']);
        $data = $model->getindexdata($get['page'] ?? 1);
        return ResponeMessage::sucessMsg("获取成功!", json_decode($data));
    }


    /**
     * 不知道干啥 反正最后到上传文件前发下这个请求
     * @return array|bool
     */
    public function putinAction()
    {
        $request = $this->getRequest();
        $userModel = UserModel::getUserModel($request);
        $model = new WeChatOpenLoginModel($userModel);

        $get = $request->getQuery();
        if (empty($get['g_tk']) || empty($get['appid'])) {
            return ResponeMessage::clientErrMsg("错误信息:" . "g_tk,appid数据为空!");
        }

        $appid = $get['appid'];
        $g_tk = $get['g_tk'];
        $model->setGTk($g_tk);

        $data = $model->putin($appid);
        //以下复制过来的 并不知道是什么逻辑
        $d = explode('&', $data);
        $token = $d[3];

        $fp = file($userModel->getCookieFile() . "cookie.txt");
        $data22 = [$fp[count($fp) - 4], $fp[count($fp) - 3], $fp[count($fp) - 2]];

        foreach ($data22 as $k => $v) {
            file_put_contents($userModel->getCookieFile() . "cookie1.txt", $v, FILE_APPEND);
        }

//        $a = PutinDataModel::returnData();
//
//        $code = 'args=' . json_encode($a) . '&' . $token . '&appid=' . '&spid=&_=' . time() . '110';
        $model->putOn($token);
        return ResponeMessage::sucessMsg("ok");
    }


    /**
     * 上传文件投放接口
     * @return array|bool
     */
    public function importFileAction()
    {
        set_time_limit (0);
        $request = $this->getRequest();
        $userModel = UserModel::getUserModel($request);
        $model = new WeChatOpenLoginModel($userModel);

        $get = $request->getQuery();
        if (empty($get['appid'])) {
            return ResponeMessage::clientErrMsg("错误信息:" . "appid数据为空!");
        }
        $appid = $get['appid'];


        //上传文件
        $upload = new Upload('file', $userModel->getDataFile() . 'excel/');

        $err = $upload->upload();
        if ($err) {
            return ResponeMessage::clientErrMsg("上传文件错误：" . $err);
        }
        //如果是压缩文件的话
        if ($upload->getExt() == "zip") {
            $zip = new \ZipArchive();
            if ($zip->open($upload->getFileSavaPath()) === true) {
                $zipPath = $userModel->getDataFile() . 'unsetzip/';
                if (!file_exists($zipPath)) {
                    mkdir($zipPath, 0777, true);
                }
                $zip->extractTo($zipPath);
                $zip->close();
                unlink($upload->getFileSavaPath());
                return ResponeMessage::sucessMsg("投放成功");
            }

            return ResponeMessage::clientErrMsg("格式有误");
        }


        //excel 逻辑
        $excel = new PaserExcelModel($upload->getFileSavaPath());
        list($api, $result) = $excel->getDataArr();
        unlink($excel);


        $result['appid'] = $appid;
        $result['user'] = (Array)$userModel;
        $postData = json_encode($result);


        $data = HttpClient::request($userModel, $api, "", 250, $postData);
        return ResponeMessage::sucessMsg("投放成功", json_decode($data));

    }
}